package com.cmhk.zmail

class MailInterceptor {
    MailTokenService mailTokenService

    MailInterceptor() {
        match(controller: "mail")
    }

    boolean before() {
        def zMailUser = session['Z_MAIL_USER']
        if(zMailUser){
            return true
        }else{
            def authRequest = request.getCookie("Z_MAIL_AUTH")
            if(authRequest){
                response.deleteCookie("Z_MAIL_AUTH")
                def username = params['username']
                def password = params['password']
                println "login with ${username} + ${password}"
                if(username&&password){
                    def token = mailTokenService.getToken(username,password)
                    try{
                        def auth = mailTokenService.authenticate(token)
                        if(auth){
                            session['Z_MAIL_USER'] = [username:username,password:password]
                            response.setCookie("Z_MAIL_TOKEN",token)
                            return true
                        }else{
                            flash.error = "username and password not match"
                        }
                    }catch(e){
                        flash.error = e.getCause()
                    }

                }else{
                    flash.error = "username and password not found"

                }
                render view:"login"
                return false
            }else{
                def token = request.getCookie('Z_MAIL_TOKEN')
                println "find Z_MAIL_TOKEN in cookie = ${token}"
                if(token){
                    if(mailTokenService.authenticate(token)){
                        session['Z_MAIL_USER'] = mailTokenService.decryptToken(token)
                        return true
                    }else{
                        response.deleteCookie('Z_MAIL_TOKEN')
                        render view:"login"
                        return false
                    }
                }else{
                    render view:"login"
                    return false
                }
            }


        }


    }

    boolean after() { true }

    void afterView() {
        // no-op
    }
}
